package com.shxc.smarttrade.tigerwit.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;

import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.myview.CustomDialog2;
import com.shxc.smarttrade.utils.GlideImageLoader;
import com.shxc.smarttrade.utils.Loger;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.OnClick;
public class TigerwitOpenAccountActivity extends Activity {

    TextView tvCenter;
    WebView webview;

    private ProgressDialog longDialog;
    private ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> uploadMessage;
    private CustomDialog2 menuDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_open_account);
        initView();
        initGallery();
    }

    private void initView() {
        initDialogs();
        longDialog.show();
        tvCenter = findViewById(R.id.tv_center);
        webview = (WebView) findViewById(R.id.webview);
        Intent intent = getIntent();
        String url = intent.getStringExtra("url");
        tvCenter.setText("交易开户");

        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webview.clearCache(true);

        webview.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    // 网页加载完成
                    longDialog.dismiss();
                }

            }

            // For 3.0+ Devices (Start)
            // onActivityResult attached before constructor
            protected void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
//                getImageFromAlbum();
                showMenuDialog();
            }


            // For Lollipop 5.0+ Devices
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }
                
                uploadMessage = filePathCallback;
                showMenuDialog();
                return true;
            }

            //For Android 4.1 only
            protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;

                showMenuDialog();
//                getImageFromAlbum();
            }

            protected void openFileChooser(ValueCallback<Uri> uploadMsg) {

                mUploadMessage = uploadMsg;
                showMenuDialog();
//                getImageFromAlbum();
            }

        });

        webview.loadUrl(url);
    }

    @OnClick(R.id.rl_left)
    public void onViewClicked() {
        if (webview.canGoBack()) {
            webview.goBack();
        } else
            finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
            webview.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 显示dialog
     */
    private void showMenuDialog() {
        if (menuDialog == null) {
            initMenuDialog();
        }
        menuDialog.show();
    }

    /**
     * 初始化dialog
     */
    private void initMenuDialog() {
        menuDialog = new CustomDialog2(this, R.style.customDialogStyle);
        menuDialog.setCanceledOnTouchOutside(true);
        //监听dialog 取消状态，并设置ValueCallback 为null以及onReceiveValue传递null,否则点击不会有回调
        menuDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }
                if (mUploadMessage != null) {
                    mUploadMessage.onReceiveValue(null);
                    mUploadMessage = null;
                }
            }
        });
        menuDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });
        menuDialog.setTakePhotoRunnable(new Runnable() {
            @Override
            public void run() {
                //TODO 拍照
                initPermissions2();
            }
        });
        menuDialog.setTakePictureRunnable(new Runnable() {
            @Override
            public void run() {
                //TODO 选择照片
                initPermissions();
            }
        });

        menuDialog.setTakeCancle(new Runnable() {
            @Override
            public void run() {
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }
                if (mUploadMessage != null) {
                    mUploadMessage.onReceiveValue(null);
                    mUploadMessage = null;
                }
            }
        });
    }

    /**
     * 初始化用于加载的dialog
     */
    private void initDialogs() {
        longDialog = new ProgressDialog(this);
        longDialog.setMessage("正在前往经纪商网站,预计10～20秒");
        longDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        longDialog.setCancelable(false);
        longDialog.setIndeterminate(false);
    }

    private void upImg(String str){
        File file = new File(str);
        Uri uri = Uri.fromFile(file);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (uploadMessage == null)
                return;
            uploadMessage.onReceiveValue(new Uri[]{uri});
            uploadMessage = null;
        } else {
            if (mUploadMessage == null)
                return;
            mUploadMessage.onReceiveValue(uri);
            mUploadMessage = null;
        }
    }

    private final int PERMISSIONS_REQUEST_READ_CONTACTS = 8;
    private final int PERMISSIONS_REQUEST_CAMERA = 9;

    private GalleryConfig galleryConfig;
    private IHandlerCallBack iHandlerCallBack;

    private List<String> path = new ArrayList<>();

    //初始化图库
    private void initGallery() {

        iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                Loger.e("initGallery", "onStart: 开启");
            }

            @Override
            public void onSuccess(List<String> photoList) {
                Loger.e("initGallery", "onSuccess: 返回数据");
                path.clear();
                for (String s : photoList) {
                    Loger.e("initGallery", s);
                    path.add(s);
                }
                for (int i = 0; i < path.size(); i++) {
                    Loger.e("path：", path.get(i));
                }
                upImg(path.get(0));
            }

            @Override
            public void onCancel() {
                Loger.e("initGallery", "onCancel: 取消");
            }

            @Override
            public void onFinish() {
                Loger.e("initGallery", "onFinish: 结束");
            }

            @Override
            public void onError() {
                Loger.e("initGallery", "onError: 出错");
            }
        };

        galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())    // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)     // 监听接口（必填）
                .provider("com.shxc.smarttrade.fileprovider")   // provider(必填)
                .pathList(path)                         // 记录已选的图片
                .multiSelect(false)                      // 是否多选   默认：false
                .multiSelect(false, 1)                   // 配置是否多选的同时 配置多选数量   默认：false ， 9
                .maxSize(1)                             // 配置多选时 的多选数量。    默认：9
                .crop(false)                             // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .crop(true, 1, 1, 512, 512)             // 配置裁剪功能的参数，   默认裁剪比例 1:1
                .isShowCamera(false)                     // 是否现实相机按钮  默认：false
                .filePath("/SmartTrade/Pictures")          // 图片存放路径
                .build();
    }

    // 授权管理 - 相册
    private void initPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(this, "请在 setting-应用管理 中开启此应用的储存授权。", Toast.LENGTH_SHORT).show();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
            GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(this);
        }
    }

    // 授权管理 - 相机
    private void initPermissions2() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSIONS_REQUEST_CAMERA);
                return;
            } else {
                GalleryPick.getInstance().setGalleryConfig(galleryConfig).openCamera(this);
            }
        } else {
            GalleryPick.getInstance().setGalleryConfig(galleryConfig).openCamera(this);
        }
    }

    // 授权返回
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {

        switch (requestCode) {
            case PERMISSIONS_REQUEST_READ_CONTACTS:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Loger.e("initPermissions", "同意授权");
                    GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(this);
                } else {
                    Loger.e("initPermissions", "拒绝授权");
                }
                break;
            case PERMISSIONS_REQUEST_CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    GalleryPick.getInstance().setGalleryConfig(galleryConfig).openCamera(this);
                } else {
                    // Permission Denied
                    Toast.makeText(this, "很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}